/*
 * @name: **列表
 * @content: 
 * @Author: joyce
 * @Date: 2020-05-29 15:38:26
 */
const express = require('express');
const router = express.Router();
var multer = require("multer");
const fs = require('fs');
const path = require('path');
const question = require('../model/question')
const question_reply = require('../model/question_reply')
const recommend = require('../model/recommend')

// 这里dest对应的值是你要将上传的文件存的文件夹
// var upload = multer({dest:'./public/images'});
// 使用硬盘存储模式设置存放接收到的文件的路径以及文件名
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    // 接收到文件后输出的保存路径（若不存在则需要创建）
    cb(null, path.join(__dirname, "../public/images/questionimg/"));
  },
  filename: function (req, file, cb) {
    // 将保存文件名设置为 时间戳 + 文件原始名，比如 151342376785-123.jpg
    let extname = file.mimetype.split('/')[1];
    let imgname = Date.now() + parseInt(Math.random() * 999) + parseInt(Math.random() * 2222);
    let keepname = imgname + '.' + extname

    cb(null, keepname);
  }
});

// 创建 multer 对象
var upload = multer({
  storage: storage
});

router.post('/api/v1/uploadImagequestion', upload.fields([{
  name: 'images'
}]), function (req, res) {
  let filesData = req.files
  let formData = JSON.parse(req.body.formData)
  console.log(formData)
  if (!!filesData.images) {
    formData.images = filesData.images[0].filename
  }
  console.log(formData)
  const info = new question(formData);
  info.save(function (err) {
    if (err) {
      console.log(err);
      res.status(500).send(err);
    } // 已保存 
    res.json({
      code: 200,
      data: 'succse'
    })
  });
})


router.post('/api/v1/put_questionImageTests', function (req, res) {
  console.log("req")
  console.log(req.body)
  question.remove({
      _id: req.body._id
  },async function (err, doc) {
      if (err) {
          res.json({
              code: 400,
              message: "err"
          });
      } else {
            //删除主图图片
          if(!!req.body.images){
            var filepath = path.join(__dirname, '../public/images/questionimg/') + req.body.images
                fs.unlink(filepath, function (err) {
                console.log(err)
                console.log("err==")
          })
            }

            await question_reply.deleteMany({
              question_id: req.body._id
            })
             //删除推荐
            await recommend.deleteOne({
              questionid: req.body._id
            })
            res.json({
            code: 200,
            mess: "succse"
            });
          
          
      }

  })
})

module.exports = router